package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {

    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.driverClass}")
    private String driverClass;
    @Value("${jdbc.user}")
    private String user;
    @Value("${jdbc.password}")
    private String password;

    /**
     * Bean注解和Autowired一样，先类型，后变量名
     *
     * @param ds
     * @return
     */
    @Bean("mRunner")//为了确保Dao层Autowired注解的正确性，这里需要跟Dao层的变量名一致
    @Scope("prototype")
    public QueryRunner createRunner(DataSource ds) {
        return new QueryRunner(ds);
    }

    @Bean("ds")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setJdbcUrl(jdbcUrl);
            dataSource.setDriverClass(driverClass);
            dataSource.setUser(user);
            dataSource.setPassword(password);
            return dataSource;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }
}
